package com.chhuang.ewcrm.ctrl;

import com.chhuang.ewcrm.api.AppRequest;
import com.chhuang.ewcrm.api.ServiceRxSchedulers;
import com.chhuang.ewcrm.api.ServiceSubscriber;
import com.chhuang.ewcrm.config.PropertiesUtil;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.thread.AddLogThread;
import com.chhuang.ewcrm.utils.*;
import com.jfoenix.controls.JFXButton;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author chhuang
 * @create 2020-10-31-10:24
 */
public class SelfInfoController implements InitController{
    private static final Logger logger = LoggerFactory.getLogger(SelfInfoController.class);

    @FXML
    private JFXButton userphotoJFXButton;
    final FileChooser fileChooser = new FileChooser();
    @FXML
    private ImageView userIconImageView;
    @FXML
    private TextField usernameTextField;
    @FXML
    private TextField fullnameTextField;
    @FXML
    private TextField userphoneTextField;
    @FXML
    private TextField usersphoneTextField;
    @FXML
    private TextField emailTextField;
    @FXML
    private JFXButton saveJFXButton;

    private final LengthTextFilter lengthTextFilter = new LengthTextFilter();

    private static String BASE_URL = PropertiesUtil.getValue(MyPath.getConfigPath()+Constants.PROPERTIES_FILE_NAME, Constants.PS_BASE_URL_STR);

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        usernameTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        fullnameTextField.setTextFormatter(new TextFormatter<>(lengthTextFilter));
        userphoneTextField.setTextFormatter(new TextFormatter<>(new IntTextFilter(11)));
        usersphoneTextField.setTextFormatter(new TextFormatter<>(new IntTextFilter(5)));
        emailTextField.setTextFormatter(new TextFormatter<>(new LengthTextFilter(127)));

        //选择用户头像
        userphotoJFXButton.setOnAction(event -> {
            fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("PNG", "*.png"));
            File userPhoto = fileChooser.showOpenDialog((Stage) ((Node) event.getSource()).getScene().getWindow());
            if(userPhoto!=null) {
                logger.debug(userPhoto.toURI().toString());//file:/E:/江苏广福/福聚源墙体画/4605.jpg_wh1200.jpg
                Image image = new Image(userPhoto.toURI().toString());
                userIconImageView.setImage(image);
            }
        });

        //初始化用户信息
        initUserInfo();

        //保存用户信息
        saveJFXButton.setOnAction(event -> {
            SysUser user = Constants.loginUser;

            String fullname = fullnameTextField.getText();
            user.setFullname(fullname);

            String phone = userphoneTextField.getText();
            if(StringUtils.isEmpty(phone)){
                MyAlert.showError("错误","修改个人信息有误","请输入用户手机号");
                userphoneTextField.requestFocus();
                return;
            }
            user.setUserphone(phone);

            String sphone = usersphoneTextField.getText();
            user.setUsersphone(sphone);

            String email = emailTextField.getText();
            user.setEmail(email);

            AppRequest.getInstance().getService().editUserInfo(user)
                    .compose(ServiceRxSchedulers.compose())
                    .subscribe(new ServiceSubscriber<>("修改个人信息") {
                        @Override
                        protected void onHandleSuccess(SysUser sysUser) {
                            Constants.loginUser = sysUser;
                            //如果用户头像存在修改用户头像;
                            String imageUrl = userIconImageView.getImage().getUrl();
                            if(imageUrl.startsWith("file")){
                                File photo = new File(imageUrl.substring(6));
                                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), photo);
                                MultipartBody.Builder builder = new MultipartBody.Builder()
                                        .setType(MultipartBody.FORM)//表单类型
                                        .addFormDataPart("userId", sysUser.getUserId())
                                        .addFormDataPart("userphoto", photo.getName(), imageBody);

                                AppRequest.getInstance().getService().uploadPhoto(builder.build().parts())
                                        .compose(ServiceRxSchedulers.compose())
                                        .subscribe(new ServiceSubscriber<>("上传用户头像") {
                                            @Override
                                            protected void onHandleSuccess(String userPhoto) {
                                                Constants.loginUser.setUserphoto(userPhoto);
                                                MyAlert.showAlertLater("成功","修改个人信息完成","");
                                            }
                                        });
                            }else {
                                MyAlert.showAlertLater("成功","修改个人信息完成","");
                            }
                            new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                                    Constants.loginUser.getUsername(),
                                    Constants.loginUser.getFullname(),
                                    "修改个人信息成功")).start();
                        }
                    });

        });
    }

    private void initUserInfo() {
        SysUser user = Constants.loginUser;
        if(StringUtils.isNotEmpty(user.getUserphoto())) {
            Image image = new Image(BASE_URL+user.getUserphoto());
            userIconImageView.setImage(image);
        }
        usernameTextField.setText(user.getUsername());
        fullnameTextField.setText(user.getFullname());
        userphoneTextField.setText(user.getUserphone());
        usersphoneTextField.setText(user.getUsersphone());
        emailTextField.setText(user.getEmail());
    }


    @Override
    public void close() {

    }
}
